import React from 'react'
// ===================================================================== Temp
import FormModal from '#cpt/temp/FormModal'
import Table from '#cpt/temp/Table'
import Input from '@antd/form/input'
import Select from '@antd/form/select'
import TableControls from '#cpt/temp/TableControls'
// ===================================================================== global declare
const { $fn, $Lazy,$http } = window
// ===================================================================== Lazy
const $cache 	= $Lazy.file(()=>import('#private/cache-api'))
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		pag: {},
		selectedKeys:[],
		toalPrice:0,
		//修改账期
		formData:[
			{ label: '回款日期',		name: 'collection_date', 	type: 'date-time',format:1,  required:true, width:'33%' },
			{ label: '受检单位',		name: 'hosp_id', 			type:'select', loading:true,required:true, width:'33%',
				onValue:({value,formData})=>{
					this.getBill()
				}
			 },
			{ label: '开票单位',		name: 'organization_name', width:'33%' },
			{ label: '区域',			name: 'region_id', 			type:'select',required:true, loading:true, width:'33%' },
			{ label: '业务员',		name: 'salesman_id', 		type:'select',required:true, width:'33%', nameStr:'real_name', idStr:'salesman_id' },
			{ type:'cpt', full:true, component:()=>{
				return(
					<div className='fv w' style={{height:250}}>
						{ Table.call(this,{type:-1, isIndex:1, hasCurrent: false}) }
					</div>
				)
			} },
			{ type:'cpt', full:true, component:()=>{
				return(
					<div className='fxr w pr20'>
						<div>小计</div>
						<div className='ml20'>收款金额：<span className='b' style={{color:'red'}}>{this.state.toalPrice}</span></div>
						<div className='ml20'>大写金额：<span className='b' style={{color:'red'}}>{this.numberChinese(this.state.toalPrice)}</span></div>
					</div>
				)
			} },
			{ type:'cpt', full:true, component:()=>{
				return(
					<div className='ml10 r5px cf bcm plr10 lh30 tc mb10' style={{width:60}} onClick={()=>{
						let { data } = this.state
						data.forEach((v,i) => v.index = i)
						data.push({summary_sn:'',bill_price:'', index: data.length })
						this.setState({data:[...data]})
					}}>添加</div>
				)
			} },
			{ label: '备注',		name: 'remark', 		type: 'textarea', 	full:true,	loading:true, required:true },
			// { label: '制表',		name: 'add_user_id', 	type: 'select', 	width:'25%',	loading:true, required:true },
			// { label: '审核',		name: 'audit_user_id', 	type: 'select', 	width:'25%',	loading:true, required:true },
		]
	}
	
	model = {}
	
	open = (data) => {
		this.modal.open({ formRef:this.formRef })
		this.getSelect(data)
	}

	// 获取下拉数据
	getSelect = (data) => {
		const { formData } = this.state
		$cache.then( async f => {
			// 业务员
			// $fn.setRow(formData, 'salesman_id', await f.getCache({ api:'salesman' } ) )
			// 医院名称
			$fn.setRow(formData, 'hosp_id', await f.getCache({ api:'hospital' } ) )
			// 区域
			$fn.setRow(formData, 'region_id', await f.getCache({ api:'bs_area' } ) ) 
			// 制表
			// $fn.setRow(formData, 'add_user_id', await f.getCache({ api:'Employee/select' } ) )
			 // 审核
			 // $fn.setRow(formData, 'audit_user_id', await f.getCache({ api:'Employee/select' } ) ) 
			 // 账期
			const summaryData = await f.getCache({ api:'bill-summary/select' } ) 
			this.summaryData = summaryData
			this.setState({ formData, summaryData })
		})
	}
	
	// 表单
	cols = [
		{ title: '账期', 		dataIndex: 'summary_sn', 	width:150, render:(text,row, index)=>{
			let { summaryDatas, summaryData, data } = this.state
			return <Select
				p = '请选择账期'
				data = {summaryDatas ?? summaryData}
				onChange={ value =>{
					const {hosp_id} = this.formRef.getValue(['hosp_id'])
					if(value&&hosp_id)this.getBill({hosp_id,summary_sn:value})
					row['summary_sn'] = value
					this.setState({})
				}}
				onDropdownVisibleChange = { bool =>{
					if(bool){
						let summaryData = $fn.copy( this.summaryData )
						// let stack = []
						data.forEach( v => {
							summaryData.forEach( ({ value }, i) => {
								if( value === v['summary_sn'] && value !== row['summary_sn'] ){
									summaryData[i] = {}
								}
							})
						})
						summaryData = summaryData.filter( v => $fn.hasObject(v))
						this.setState({ summaryDatas:summaryData } )
					}
				}}
			 />
		} },
		{ title: '账单金额', 	dataIndex: 'bill_price', 		...$fn.table.num},
		{ title: '已收款金额', 	dataIndex: 'proceeds', ...$fn.table.num },
		{ title: '收款金额', 	dataIndex: 'collection_price', 		...$fn.table.num, render:(text,row)=>{
			return <Input
				readOnly={!row.summary_sn}
				onChange={ value =>{
					const { data }= this.state
					row['collection_price'] = value
					row['not_collection_price'] = (row.bill_price - row.proceeds - row.collection_price).toFixed(2)
					this.setState(() => {
						const d = this.state.data.map( v => +v['collection_price'] ?? 0)
						return { toalPrice: d.reduce((t,v)=> t+v ), data: [...data] }
					})
					
					this.fromData = this.state.data.map( v => ({ summary_sn:v.summary_sn, collection_price:v.collection_price }))
				}}
			/>
		} },
		{ title: '未收款金额', 	dataIndex: 'not_collection_price', 		...$fn.table.num },
		TableControls.controls.call(this, { width: 80 })
	]
	
	// 表格操作按钮
	table_controls = (text, {index}) => {
		return [
			TableControls.del.call(this, { refresh:false,  onOk: (close) => {
				let { data } = this.state
				let toalPrice = 0
				data.splice(index, 1)
				data.forEach((v,i) => {
					v.index = i
					toalPrice += parseInt(v.collection_price)
				})
				this.setState({data:[...data], toalPrice})
				close()
			} })
		]
	}
	
	getBill = param => {
		const { formData, data} = this.state
		$http.submit(null,'fi-standing-book/getHospSummaryPrice',{param:{...param, type:2}}).then(res=>{
			const {salesman,summary_sn,bill_info, hosp} = res
			$fn.setRow(formData, 'salesman_id', salesman )
			data.forEach((v,i)=>{
				if(v.summary_sn === summary_sn.summary_sn){
					data[i].bill_price = bill_info.bill_price
					data[i].proceeds = bill_info.collection_price
					data[i].not_collection_price = bill_info.not_collection_price
					this.formRef.setValue({organization_name:hosp.organization_name,region_id:hosp.region})
				}
			})
			this.setState({ formData,data })
		})
	}
	numberChinese = str=>{
		var num = parseFloat(str);
		var strOutput = "",
		strUnit = '仟佰拾亿仟佰拾万仟佰拾元角分';
		num += "00";
		var intPos = num.indexOf('.'); 
		if (intPos >= 0){
			num = num.substring(0, intPos) + num.substr(intPos + 1, 2);
		}
		strUnit = strUnit.substr(strUnit.length - num.length);
		for (var i=0; i < num.length; i++){
			strOutput += '零壹贰叁肆伍陆柒捌玖'.substr(num.substr(i,1),1) + strUnit.substr(i,1);
		}
		return strOutput.replace(/零角零分$/, '整').replace(/零[仟佰拾]/g, '零').replace(/零{2,}/g, '零').replace(/零([亿|万])/g, '$1').replace(/零+元/, '元').replace(/亿零{0,3}万/, '亿').replace(/^元/, "零元")
	}
	render(){
		return FormModal.call(this,{ title:'填写回款单',width:'50%', api: 'fi-pay-book/addCollection',
			getSubmit: param => {
				param['from_data'] = this.fromData
				return param
			},
			close:()=>{
				this.setState({data:[], toalPrice: 0})
			}
		})
	}
}

export default Index